package com.dawn.seckilldemo.config;

import com.dawn.seckilldemo.pojo.User;
import com.dawn.seckilldemo.service.UserService;
import com.dawn.seckilldemo.utils.CookieUtil;
import com.dawn.seckilldemo.vo.RespBean;
import com.dawn.seckilldemo.vo.RespBeanEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class AccessLimitInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            User user = getUser(request,response);
            //存入threadlocal中
            UserContext.setUser(user);
            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null){
                //没有，直接放行
                return true;
            }
            int second = accessLimit.second();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            String uri = request.getRequestURI();
            if(needLogin){
                if(user==null){
                    render(response, RespBeanEnum.SESSION_ERROR);
                    return false;
                }
            }
                String key = uri+":"+user.getId();
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Integer count = (Integer) valueOperations.get(key);
            //查看计数器，判断计数器
            if(count == null) {
                valueOperations.set(uri + ":" + user.getId(), 1, second, TimeUnit.SECONDS);
            }else if(count <maxCount){
                valueOperations.increment(uri + ":" + user.getId());
            }else {
                //返回错误信息
                render(response,RespBeanEnum.ACCESS_LIMIT_REAHCED);
                return false;
            }


        }

        return true;
    }

    //构建返回对象
    private void render(HttpServletResponse response, RespBeanEnum sessionError) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        RespBean error = RespBean.error(sessionError);
        out.write(new ObjectMapper().writeValueAsString(error));
        out.flush();
        out.close();


    }

    //获取当前用户
    private User getUser(HttpServletRequest request, HttpServletResponse response) {
        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        if(StringUtils.isEmpty(ticket)){
            return null;
        }

        return userService.getUserByCookie(ticket,request,response);
    }
}
